package com.aqie.rabbit.service.Impl;

import com.aqie.rabbit.bean.api.group.GroupCreateModel;
import com.aqie.rabbit.bean.db.Group;
import com.aqie.rabbit.bean.db.GroupMember;
import com.aqie.rabbit.bean.db.User;
import com.aqie.rabbit.repositories.GroupMemberRepository;
import com.aqie.rabbit.repositories.GroupRepository;
import com.aqie.rabbit.service.IGroupMemberService;
import com.aqie.rabbit.service.IGroupService;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class GroupServiceImpl implements IGroupService {

    @Autowired
    private GroupRepository groupRepository;

    @Autowired
    private GroupMemberRepository groupMemberRepository;

    @Autowired
    private IGroupMemberService groupMemberService;

    @Override
    public Group findById(String groupId) {
        return groupRepository.findById(groupId).orElse(null);
    }

    @Override
    public Group findById(User user, String groupId) {
        GroupMember member = groupMemberService.getMember(user, groupId);
        if (member != null) {
            return member.getGroup();
        }
        return null;
    }

    @Override
    public Group findByName(String name) {
        return groupRepository.findByName(name).orElse(null);
    }


    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public Group create(User creator, GroupCreateModel model, List<User> users) {
        Group group = new Group(creator, model);
        groupRepository.save(group);

        GroupMember ownerMember = new GroupMember(creator, group);
        // 设置超级权限，创建者
        ownerMember.setPermissionType(GroupMember.PERMISSION_TYPE_ADMIN_SU);
        groupMemberRepository.save(ownerMember);

        // 添加群成员
        List<GroupMember> members = new ArrayList<>();
        for (User user : users){
            GroupMember member = new GroupMember(user, group);
            members.add(member);
        }
        groupMemberRepository.saveAll(members);
        return group;
    }



    @Override
    public List<Group> search(String name) {
        if (Strings.isNullOrEmpty(name)) name = "";

        final String searchName = "%" + name + "%"; // 模糊匹配
        return groupRepository.findByNameComplete(searchName).orElse(null);
    }


}
